package com.study.lxy.springmvc.util;


import org.slf4j.MDC;

import javax.servlet.*;
import java.io.IOException;
import java.util.UUID;

public class LogbackFilter implements Filter {
    private static final String TRACE_ID = "traceId";
    @Override
    public void init(FilterConfig filterConfig) {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        boolean bInsertMDC = insertMDC();
        UserPrincipleTaker.set(new UserPrinciple("liuxingyi","simple man"));
        try {
            filterChain.doFilter(servletRequest, servletResponse);
        } finally {
            if(bInsertMDC) {
                MDC.remove(TRACE_ID);
            }
        }
    }

    private boolean insertMDC(){
        UUID uuid = UUID.randomUUID();
        String uniqueId = "T=" + uuid.toString().replace("-", "");
        MDC.put(TRACE_ID, uniqueId);
        return true;
    }

    @Override
    public void destroy() {

    }
}
